<template>
    <el-row class="home" :gutter="20">
        <!-- 左边部分 -->
        <el-col :span="8" style="margin-top: 20px">
            <!-- 用户信息卡片 -->
            <el-card shadow="hover">
                <!-- 基本信息 -->
                <div class="user">
                    <img :src="userInfo.face" alt="">
                    <!-- <img src="http://localhost:7000/assets/uploads/123.jpg" alt=""> -->
                    <!-- <img src="http://10.22.33.214:7000/assets/uploads/123.jpg" alt=""> -->
                    <div class="user-info">
                        <p class="name">{{userInfo.nickname}} </p>
                        <p class="role">{{userInfo.isAdmin==1?'超级管理员':'普通管理员'}}</p>
                    </div>
                </div>
                <!-- 登录信息 -->
                <div class="login-info">
                    <p>上次登录时间：<span>{{userInfo.loginTime}}</span></p>
                    <p>上次登录的地点：<span class="span2">广州</span></p>
                </div>
            </el-card>

            <!-- 商品相关信息 -->
            <el-card shadow="hover" style="margin-top: 20px">
                <el-table :data="tableData">
                    <el-table-column
                      v-for="(item,index) in tableLabel"
                      :key="index"
                      :prop="index"
                      :label="item"
                    >
                    </el-table-column>
                </el-table>
            </el-card>
        </el-col>

        <!-- 右边部分 -->
        <el-col :span="16" style="margin-top:20px" class="right-num">
            <!-- 订单销量数据 -->
            <div class="order">
                <el-card v-for="(item,index) in countData" :key="index" :body-style="{ display:'flex', padding:0 }">
                        <component class="icons" :is="item.icon" :style="{ background: item.color}"></component>
                        <div class="detail">
                            <p class="money">￥{{item.value}}</p>
                            <p class="name">{{item.name}}</p>
                        </div>
                </el-card>
            </div>
            <!-- eChart折线图 -->
            <el-card style="height:280px">
                <div ref="echart" style="height:280px"></div>
            </el-card>
            <div class="graph">
                <!-- 柱状图 -->
                <el-card style="height: 260px">
                    <div ref="userechart" style="height: 260px"></div>
                </el-card>
                <!-- 饼状图 -->
                <el-card style="height: 260px">
                    <div ref="videoechart" style="height: 240px"></div>
                </el-card>
            </div>
        </el-col>
    </el-row>
</template>

<script setup>
import { ref,onMounted,getCurrentInstance,reactive } from 'vue'
import { getProductSale,getOrderData,getPersonInfo } from '../api/manager'
import { userStore } from '../store/index'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'

const { proxy } = getCurrentInstance()
const router = useRouter()
const uStore = userStore()
const userInfo = reactive({
  face:'',
  nickname:'',
  isAdmin:'',
  loginTime:''
})
const countData = ref([])
const tableLabel = {
    name:'手机品牌',
    todayBuy:'今日销售量',
    monthBuy:'本月销售量',
    totalBuy:'总销售量'
}
const tableData = ref([])

// 关于echarts 表格的渲染部分
let xOptions = reactive({
      // 图例文字颜色
      textStyle: {
        color: "#333",
      },
      grid: {
        left: "20%",
      },
      // 提示框
      tooltip: {
        trigger: "axis",
      },
      xAxis: {
        type: "category", // 类目轴
        data: [],
        axisLine: {
          lineStyle: {
            color: "#17b3a3",
          },
        },
        axisLabel: {
          interval: 0,
          color: "#333",
        },
      },
      yAxis: [
        {
          type: "value",
          axisLine: {
            lineStyle: {
              color: "#17b3a3",
            },
          },
        },
      ],
      color: ["#2ec7c9", "#b6a2de", "#5ab1ef", "#ffb980", "#d87a80", "#8d98b3"],
      series: [],
    });
    let pieOptions = reactive({
      tooltip: {
        trigger: "item",
      },
      color: [
        "#0f78f4",
        "#dd536b",
        "#9462e5",
        "#a6a6a6",
        "#e1bb22",
        "#39c362",
        "#3ed1cf",
      ],
      series: [],
    });
    let orderData = reactive({
      xData: [],
      series: [],
    });
    let userData = reactive({
      xData: [],
      series: [],
    });
    let videoData = reactive({
      series: [],
    });

 // 获取数据
 const getChartData = async () => {
      let result = await proxy.$api.getChartData();
      // console.log(result);
      let res = result.orderData;
      let userRes = result.userData;
      let videoRes = result.videoData;
      orderData.xData = res.date;
      const keyArray = Object.keys(res.data[0]);
      const series = [];
      keyArray.forEach((key) => {
        series.push({
          name: key,
          data: res.data.map((item) => item[key]),
          type: "line",
        });
      });
      orderData.series = series;
      xOptions.xAxis.data = orderData.xData;
      xOptions.series = orderData.series;
      // userData进行渲染
      let hEcharts = echarts.init(proxy.$refs["echart"]);
      hEcharts.setOption(xOptions);

      // 柱状图进行渲染的过程
      userData.xData = userRes.map((item) => item.date);
      userData.series = [
        {
          name: "新增用户",
          data: userRes.map((item) => item.new),
          type: "bar",
        },
        {
          name: "活跃用户",
          data: userRes.map((item) => item.active),
          type: "bar",
        },
      ];

      xOptions.xAxis.data = userData.xData;
      xOptions.series = userData.series;
      let uEcharts = echarts.init(proxy.$refs["userechart"]);
      uEcharts.setOption(xOptions);
      videoData.series = [
        {
          data: videoRes,
          type: "pie",
        },
      ];
      pieOptions.series = videoData.series;
      let vEcharts = echarts.init(proxy.$refs["videoechart"]);
      vEcharts.setOption(pieOptions);
    };

onMounted(()=>{
    // axios.get('/home/getTableData').then(res => tableData.value = res.data)
    //获取用户个人信息
    //如果session中没有缓存则发起请求
    if(!sessionStorage.getItem('userInfo')){
      console.log('request');
      const params = { user_id:localStorage.getItem('user_id') }
      getPersonInfo(params).then(res =>{
        if(res.code == 200){
            userInfo.face = res.data.face
            userInfo.nickname = res.data.nickname
            userInfo.isAdmin = res.data.is_admin
            userInfo.loginTime = res.data.login_time
            //存一份到pinia中
            uStore.setAdmin(res.data.is_admin)
            //存一份到session中
            sessionStorage.setItem('userInfo',JSON.stringify(res.data))
        }else if(res.code == 252){
            ElMessage.error('身份认证过期，请重新登陆')
            localStorage.clear()
            router.push('/login')
        }else{
            ElMessage.error(res.msg)
        }
      })
    //如果session中有缓存则直接拿数据
    }else{
      console.log('noRequest');
      const myUserInfo = JSON.parse(sessionStorage.getItem('userInfo'))
      userInfo.face = myUserInfo.face
      userInfo.nickname = myUserInfo.nickname
      userInfo.isAdmin = myUserInfo.is_admin
      userInfo.loginTime = myUserInfo.login_time
    }
    getProductSale().then(res => tableData.value = res.data)
    getOrderData().then(res => countData.value = res.data)
    if(localStorage.getItem('token')){
      //获取echarts图表数据
      getChartData()
    }
})

</script>

<style lang="less" scoped>
    .home{
        .user{
            display: flex;
            align-items: center;
            padding-bottom: 20px;
            border-bottom: 1px solid #ccc;
            margin-bottom: 20px;
            img{
                object-fit: cover;
                // background-size: cover;
                width: 150px;
                height: 150px;
                border-radius: 50%;
                margin-right: 40px;
            }

            .user-info{
                .name{
                    font-size: 30px;
                    font-weight: bold;
                }
                .role{
                    margin-top: 10px;
                    font-size: 16px;
                    color: rgb(10, 166, 227);
                }
            }
        }

        .login-info{
                p{
                    line-height: 30px;
                    font-size: 14px;
                    color: #999;
                    span{
                        color:#666;
                        margin-left: 50px;
                    }
                    .span2{
                        margin-left: 36px;
                    }
                }
            }


            .order{
                display: flex;
                justify-content: space-between;
                flex-wrap: wrap;
                
                .el-card{
                    width:32%;
                    margin-bottom:20px
                }
                .icons{
                    width:80px;
                    height:80px;
                    font-size: 30px;
                    text-align: center;
                    color: white;
                    line-height: 80px;
                }

                .detail{
                    display: flex;
                    flex-direction: column;
                    margin-left: 14px;
                    justify-content: center;

                    .money{
                        font-size: 26px;
                    }
                    .name{
                        font-size: 14px;
                        color: #999;
                    }
                }
            }

            .graph {
                margin-top: 20px;
                display: flex;
                justify-content: space-between;
                .el-card {
                width: 48%;
                }
            }
        
    }
</style>